var gridList, moduleId, checked;
var selectedModule = new Object();
var currentTreeNode = null;
var defPsMap = new Map();
var orgMap = new Map();
var ognMap = new Map();
var privilageMap = new Map();
var defPsArray = new Array();
var table, isAdmin, lastCheckedDep;

layui.config({
    base: '/static/lib/layuiadmin/',
}).extend({
    authtree: 'modules/authtree',
    authtree_zimi: 'modules/authtree_zimi'
}).use(['jquery', 'authtree_zimi', 'form', 'layer'], function () {
    table = layui.table;
    authtree = layui.authtree_zimi;
    loadTree();

});

$(document).ready(function () {
    $('#upOrgBtn').bind('click', upOrgBtn);
    $('#downOrgBtn').bind('click', downOrgBtn);
    $('#addOrgBtn').bind('click', addOrgCB);
    $('#changeBtn').bind('click', changeDepartment);
    $('#add').bind('click', add);
    $('#editOrgBtn').bind('click', editOrgCB);
    $('#removeOrgBtn').bind('click', removeOrg);
    $('#recoverOrgBtn').bind('click', recoverOrg);
    $('.orgText').bind('click', clearOrg);
    //掩藏半公开表格和掩藏右边部分
    $('.orgPartnerText').hide();
    $('#bottom').hide();
    $('#right').hide();
    $('#top').css('height', '100%');

    //解决按钮组折行问题
    let width = document.body.offsetWidth;
    if (width < 1920) {
        $('.layui-btn-group').css('color', 'red');
    }
});

function loadTree() {
    gridList = new dataGrid("gridList");
    $.post("/sys-org-cate/allList", {}, function (data) {
        if (data.code == 0) {

            isAdmin = data.isAdmin;

            if (!isAdmin) {
                $('#top').css('height', '100%');
                $('#bottom').hide();
                $('.orgPartnerText').hide();
            }

            if (data.data.length > 0) {
                selectedModule.id = data.data[0].id;
                selectedModule.socName = data.data[0].socName;
                gridList.load({
                    'moduleId': selectedModule.id,
                    'activeFlag': 1
                });

                $('.orgText').html(`<span style="color: #F72E29">${selectedModule.socName}</span>可以查看以下机构`);

                loadOrgTree(selectedModule.id);

                var str = "";
                data.data.forEach(function (value) {
                    str += "<li><a onclick=\"selectModule('" + value.id + "','" + value.socName + "')\">" +
                        "<i class=\"layui-icon\" style='top: 1px;position: relative;' id=\"" + value.id + "\">&#xe620;</i>" +
                        "<cite>" + value.socName + "</cite>" +
                        "</a></li>"
                });
                $("#cateTree").html(str);
                $("#cateTree li i").eq(0).html("&#xe614;");
            }
        } else {
            layer.msg('取得机构分类数据失败！', {
                icon: 2,
                time: 1000 //2秒关闭（如果不配置，默认是3秒）
            }, function () {
            })
        }
    });
}

function selectModule(id, socName) {
    $("#cateTree i").html("&#xe620;");
    $("#cateTree #" + id).html("&#xe614;");
    $('#top').css('height', '100%');
    $('.orgText').css('height', '5%');
    $('#border').css('height', '95%');
    $('#org_tree').css('margin-top', '0%');
    $("#title span").html(socName);
    selectedModule.id = id;
    selectedModule.socName = socName;
    $('.orgText').html(`<span style="color: #F72E29">${selectedModule.socName}</span>可以查看以下机构`);
    currentTreeNode = null;
    $(".funText").text("");
    $(".funText1").text("");
    $('#functionTree').html("");
    //掩藏半公开表格和掩藏右边部分
    $('.orgPartnerText').hide();
    $('#bottom').hide();
    $('#right').hide();

    loadOrgTree(selectedModule.id);
}

function refreshData() {
    gridList.reload({});
}

/*
* @author: wj
* @description: 加载机构树
* @date: 2018/12/18 14:51
* @param
* @return
*/
function loadOrgTree(id) {
    moduleId = id; //刷新树时用到

    $.post("/sys-org/orgListByCate", {parentId: id}, function (data) {
        treeData = data.List;

        if (data.code == 0) {
            for (var i = 0; i < data.List.length; i++) {
                orgMap.set(data.List[i].id, data.List[i]);
            }

            $("#orgTree").html("");

            // 原先已选择节点时，更新选择节点值
            if (currentTreeNode) {
                currentTreeNode.value = orgMap.get(currentTreeNode.value.id);
            }

            let trees = formatData(data.List, "orgPid", "id", "orgName");
            authtree.render('#orgTree', trees, {
                inputname: 'authids[]',
                layfilter: 'lay-check-auth',
                autowidth: true,
                // checkType: 'radio',
                fgo: 0,
                // flags: [1]
            });

            //调整机构树中radio框的样式
            // $('span input[type=radio]').parent().parent().css('height', '30px');
            // 树要显示两层
            authtree.showDept('#orgTree', 2);

            $('span[state=2]').on('click', (e) => {
                let ele = $(e)[0].currentTarget.outerHTML;
                let value = $(ele).attr('value');
                let node = eval("(" + value + ")");
                currentTreeNode = node;

                $('.orgText').html(`当前节点为：<span style="color: #F72E29">${selectedModule.socName} -- ${node.orgName}</span>`);

                if (currentTreeNode.orgPid > 0) {
                    $(".funText").html(`<span style="color: #F72E29">${node.orgName}</span>部门的领导有：`);
                    $('.orgPartnerText').html("");
                    $('#add').hide();
                    $('#top').css('height', '100%');
                    $('.orgText').css('height', '5%');
                    $('#border').css('height', '95%');
                    $('#org_tree').css('margin-top', '0%');
                    $('#bottom').css('height', '0%');
                    $('#bottom').hide();
                } else {
                    $(".funText").html(`<span style="color: #F72E29">${node.orgName}</span>单位的领导有：`);
                    $('.orgPartnerText').html(`<span style="color: #F72E29">${node.orgName}</span>可以查看以下机构`);
                    $('#top').css('height', '49%');
                    $('.orgText').css('height', '10%');
                    $('#border').css('height', '90%');
                    $('#org_tree').css('margin-top', '3%');
                    $('#bottom').css('height', '49%');
                    $('#bottom').show();
                    $('#add').show();
                }
                $(".funText1").html(`给<span style="color: #F72E29">${node.orgName}</span>授权以下功能`);

                //显示半公开表格和掩藏右边部分
                $('.orgPartnerText').show();
                $('#bottom').show();
                $('#right').show();

                if (isAdmin && currentTreeNode && currentTreeNode.orgPid == 0) {
                    $('#table').show();
                    load_partner_table(currentTreeNode.id);
                } else {
                    $('#table').hide();
                    $('.orgPartnerText').hide();
                    $("#border").removeClass('border');
                }

                load_leader_table(currentTreeNode.id);
                load_function_tree(currentTreeNode.id);

            });

         /*   authtree.on('change(lay-check-auth)', function (data) {
                let checked = authtree.getChecked('#orgTree'); //获取最新选中
                let node = eval("(" + checked + ")");
                //点击树事件
                currentTreeNode = node;

                $('.orgText').html(`当前节点为：<span style="color: #F72E29">${selectedModule.socName} -- ${node.orgName}</span>`);

                if (currentTreeNode.orgPid > 0) {
                    $(".funText").html(`<span style="color: #F72E29">${node.orgName}</span>部门的领导有：`);
                    $('.orgPartnerText').html("");
                    $('#add').hide();
                    $('#top').css('height', '100%');
                    $('.orgText').css('height', '5%');
                    $('#border').css('height', '95%');
                    $('#org_tree').css('margin-top', '0%');
                    $('#bottom').css('height', '0%');
                    $('#bottom').hide();
                } else {
                    $(".funText").html(`<span style="color: #F72E29">${node.orgName}</span>单位的领导有：`);
                    $('.orgPartnerText').html(`<span style="color: #F72E29">${node.orgName}</span>可以查看以下机构`);
                    $('#top').css('height', '49%');
                    $('.orgText').css('height', '10%');
                    $('#border').css('height', '90%');
                    $('#org_tree').css('margin-top', '3%');
                    $('#bottom').css('height', '49%');
                    $('#bottom').show();
                    $('#add').show();
                }
                $(".funText1").html(`给<span style="color: #F72E29">${node.orgName}</span>授权以下功能`);

                //显示半公开表格和掩藏右边部分
                $('.orgPartnerText').show();
                $('#bottom').show();
                $('#right').show();

                if (isAdmin && currentTreeNode && currentTreeNode.orgPid == 0) {
                    $('#table').show();
                    load_partner_table(currentTreeNode.id);
                } else {
                    $('#table').hide();
                    $('.orgPartnerText').hide();
                    $("#border").removeClass('border');
                }

                load_leader_table(currentTreeNode.id);
                load_function_tree(currentTreeNode.id);
            });*/

        } else {
            layer.msg('取得模块数据失败！', {
                icon: 2,
                time: 1000 //2秒关闭（如果不配置，默认是3秒）
            }, function () {
            })
        }
    });
}

function load_leader_table(id) {
    $.ajax({
        url: '/sys-org-leader/getLeader',
        data: {'orgId': id},
        type: 'post',
        dataType: 'json',
        success(res) {
            if (res.code == 0) {
                table.render({
                    elem: '#leader'
                    , method: 'post'
                    , title: '部门领导表'
                    , data: res.data
                    , even: true//隔行变色
                    , limit: 5
                    , limits: [5, 10, 15, 20, 25, 30, 35, 40]
                    , page: true //开启分页
                    , height: 330
                    , totalRow: true //开启合计行
                    , cols: [[ //表头
                        {field: 'postName', title: '岗位'}
                        , {fixed: 'right', title: '操作', align: 'center', toolbar: '#leaderBar'}
                    ]]
                });

                //监听行工具事件
                table.on('tool(leader)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                    var data = obj.data //获得当前行数据
                        , layEvent = obj.event; //获得 lay-event 对应的值
                    if (layEvent === 'del') {
                        $.ajax({
                            url: '/sys-org-leader/save',
                            type: 'post',
                            data: {
                                'id': data.id,
                                'state': 2,
                                'updateTime': data.updateTime
                            },
                            success: res => {
                                if (res.code == 0) {
                                    layer.msg("删除成功！", {icon: 1});
                                } else {
                                    layer.msg(res.msg, {icon: 5});
                                }
                            },
                            error: () => {
                                layer.msg("请求失败！", {icon: 5});
                            },
                            complete: () => {
                                load_leader_table(currentTreeNode.id);
                            }
                        });
                    } else if (layEvent === 'up') {
                        $.ajax({
                            url: '/sys-org-leader/moveUp',
                            type: 'post',
                            data: data,
                            success: res => {
                                if (res.code == 0) {
                                    layer.msg("上移成功！", {icon: 1, time: 1000});
                                    load_leader_table(currentTreeNode.id);
                                } else {
                                    layer.msg(res.msg, {icon: 4, time: 1000});
                                }
                            },
                            error: () => {
                                layer.msg("请求失败！", {icon: 5});
                            }
                        });
                    } else if (layEvent === 'down') {
                        $.ajax({
                            url: '/sys-org-leader/moveDown',
                            type: 'post',
                            data: data,
                            success: res => {
                                if (res.code == 0) {
                                    layer.msg("下移成功！", {icon: 1, time: 1000});
                                    load_leader_table(currentTreeNode.id);
                                } else {
                                    layer.msg(res.msg, {icon: 4, time: 1000});
                                }
                            },
                            error: () => {
                                layer.msg("请求失败！", {icon: 5});
                            }
                        });
                    }
                });
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        },
        error() {
            layer.msg("请求失败！", {icon: 5});
        }
    });


}

function load_function_tree(orgId) {
    layui.use('authtree', function () {
        var authtree = layui.authtree;
        // 取得岗位授权
        ActHttpRequest('/sys-org-privilege/orgFunctionList', {'orgId': orgId}, function (returnData) {
            if (returnData.code === 0) {
                // 全局变量赋值
                privilageMap.clear();

                if (returnData.List.length > 0) {
                    for (var i = 0; i < returnData.List.length; i++) {
                        privilageMap.set(returnData.List[i].functionId, returnData.List[i]);
                    }
                }

                var values = formatFunctionData(returnData, "parentId", "functionId", "name", "choiceFlag");
                authtree.render('#functionTree', values, {
                    inputname: 'authids[]'
                    , layfilter: 'lay-check-auth2'
                    , autowidth: true
                    , autochecked: false
                    , autoclose: false
                });
            }
        });

        authtree.on('change(lay-check-auth2)', function (data) {
            var lastChecked = authtree.getLastChecked('#functionTree') //获取最新选中
                , lastNotChecked = authtree.getLastNotChecked('#functionTree') // 获取最新取消
                , value // 保存值的变量
                , parents // 保存父值的变量
                , url  // 请求URL
                , values; //关联实体一览

            if (lastChecked.length > 0) {
                value = parseInt(lastChecked["0"]);
                parents = getParents([value]);
                url = "/sys-org-privilege/saveFunctionOrg";
            } else {
                value = parseInt(lastNotChecked["0"]);
                url = "/sys-org-privilege/deleteFunctionOrg";
            }

            // 取得关联子项目编号一栏，并取得实体
            var relationIds = getChilds([value]);
            if (parents && parents.length > 0) {
                relationIds = relationIds.concat(parents);
            }

            relationIds.push(value);
            values = [];
            for (var i = 0; i < relationIds.length; i++) {
                var tmpPrivilege = privilageMap.get(relationIds[i]);
                tmpPrivilege.orgId = orgId;
                values.push(privilageMap.get(relationIds[i]));
            }

            // 向服务器发出Ajax请求
            $.ajax({
                async: false,
                type: 'post',
                dataType: "json",
                url: url,
                data: {"privilageList": JSON.stringify(values)},
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                timeout: 30000,//超时时间设置为1分钟；
                success: function (data) {
                    if (data.code == 0) {
                        layer.msg("提交成功!", {icon: 1, time: 1000});
                    } else {
                        layer.msg(data.msg, {icon: 1, time: 1000});
                    }
                },
                complete: function (XMLHttpRequest, textStatus) {
                    load_function_tree(orgId);
                },
                error: function (a, b, c) {
                    // 请求出错处理,依然初始化咨询节点信息
                    if (b == 'timeout') {
                        layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
                    } else {
                        layer.alert(url + "请求异常", {title: '错误信息：'});
                    }
                }
            });
        });
    });

}

/**
 * @desc 添加部门领导
 */
function addLeader() {
    let index = layer.open({
        type: 1,
        title: '添加部门领导',
        btn: ['确定', '取消'],
        area: ['550px', '600px'],
        zIndex: layer.zIndex,
        shade: 0,
        content: $('#leaderT'),
        success() {
            $.ajax({
                url: '/sys-post-privilege/getLeaderList',
                type: 'post',
                dataType: 'json',
                async: false,
                data: {
                    'orgId': currentTreeNode.id
                },
                dataType: 'json',
                success: function (res) {
                    if (res.code == 0) {

                        let unCheckedArr = [];
                        let result = [];
                        //1 过滤得到state为1的数据
                        if (res.leaderData.length > 0) {
                            result = res.leaderData.filter(item => (item.state === 1));
                            // 2 过滤出默认岗位
                            let Array = res.leaderData.filter(item => (item.postId == 0));

                            //3 事先备用好上级岗位表中已有的数据，然后到树结构中加入其id和updateTime
                            if (Array.length > 0) {
                                Array.forEach(item => {
                                    defPsMap.set(item.orgId, item);
                                    defPsArray.push(item.orgId);
                                });
                            }
                        }

                        if (result && result.length > 0) {
                            unCheckedArr = result.map(item => `${item.orgId}-${item.postId}`);
                        }

                        var trees = formatData2(res.data, 'parentId', 'id', 'name', 'choiceFlag');

                        // 如果后台返回的不是树结构，请使用 authtree.listConvert 转换
                        authtree.render('#leaderTree', trees, {
                            inputname: 'authids[]',
                            layfilter: 'lay-check-auth',
                            autowidth: true,
                            checkType: 'radio',
                            uncheckedArr: unCheckedArr,
                            fgo: 2,
                            flags: [3]
                        });

                        authtree.on('change(lay-check-auth)', function (data) {
                            // 获取已选中节点
                            checked = authtree.getChecked('#leaderTree');
                        });

                        authtree.showDept('#leaderTree', 2);

                    } else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        },
        yes() {
            if (checked && checked.length > 0) {
                let orgId = currentTreeNode.id;
                let obj = eval("(" + checked + ")");
                let data = {
                    'id': obj.functionId,
                    'originOrgId': currentTreeNode.id,
                    'orgId': obj.orgId,
                    'postId': obj.postId,
                    'leaderSort': obj.sort,
                    'state': 1,
                    'updateTime': obj.updateTime
                }

                //保存数据入库
                $.ajax({
                    url: "/sys-org-leader/save",
                    type: 'post',
                    data: data,
                    success(res) {
                        if (res.code == 0) {
                            layer.msg("保存成功！", {icon: 1, time: 1000});
                            load_leader_table(orgId);
                        } else {
                            layer.msg(res.msg, {icon: 5, time: 1000});
                        }
                    },
                    error() {
                        layer.msg("请求失败！", {icon: 5, time: 1000});
                    }

                });
            }

            layer.close(index);
        },
        btn2() {
            layer.close(index);
        },
        end() {
            checked = '';
        }
    });
}

/**
 * 取得授权功能父节点Id一览
 */
function getParents(ids) {
    var result = [];

    var obj = privilageMap.get(ids[ids.length - 1]);
    var parent;

    // 查找上一个父节点，若没选中的状态则加到result
    if (obj.parentId > 0) {
        parent = privilageMap.get(obj.parentId);
        if (!parent.choiceFlag) {
            result.push(obj.parentId);
            result = result.concat(getParents(result));
        }
    }

    return result;
}

/**
 * wh 上移树
 * @param selectModule
 * @param node
 */
function upOrgBtn() {
    if (currentTreeNode != null) {
        let node = currentTreeNode;

        //1) 获取同级树的对象集合
        let ids = new Array();
        let idList = new Array();
        let treeMap = new Map();
        let nodePid = node.value.orgPid;
        let sort = node.value.orgSort; //当前数据的sort
        let index; //当前数据的index

        if (treeData != null && treeData.length > 0) {
            treeData.forEach(function (item, index) {
                if (item.orgPid == nodePid) {
                    ids.push(item)
                }
            });
        }

        //2) 根据id集合获取索引
        ids.forEach(function (item, index) {
            treeMap.set(item.id, index);
        });
        index = treeMap.get(node.id);

        if (sort - 1 == 0 || index == 0) { //主要sort要从1开始或者取出来的数据要按orgSort拍好序，否则此处会报错
            layer.msg('已到达顶部！', {icon: 1, time: 1000});
        } else {


            // 3) 获取上一条数据
            let upData = ids[index - 1];
            let upSort = upData.orgSort;

            // 4) 交换两条数据的orgSort
            node.value.orgSort = upSort;
            upData.orgSort = sort;

            // 5)把交换过的两条数据存入数组中
            idList.push(node.value);
            idList.push(upData);

            //6）通过ajax把数据发送到后台
            $.ajax({
                url: '/sys-org/move'
                , data: {'idList': JSON.stringify(idList)}
                , type: 'post'
                , success: function (res) {
                    if (res.code == 0) {
                        // 7) 刷新树（一定要注意更新数据库后执行此操作，不然下次上下移会报错）
                        loadOrgTree(moduleId);
                        layer.msg("上移成功！", {icon: 1, time: 1000});

                    } else {
                        layer.msg(res.msg, {icon: 5, time: 2000})
                    }

                },
                error: function (res) {
                    layer.msg(res.msg, {icon: 5, time: 2000});
                },
                complete: function () {
                    currentTreeNode = null;
                }
            });

        }
    } else {
        layer.msg('请先点击树获取最新节点数据', {icon: 3, time: 2000});
    }
}


/**
 * wh 下移树
 * @param selectModule
 * @param node
 */
function downOrgBtn() {

    if (currentTreeNode != null) {
        let node = currentTreeNode;

        //1) 获取同级树的对象集合
        let ids = new Array();
        let idList = new Array();
        let treeMap = new Map();
        let nodePid = node.value.orgPid;
        let sort = node.value.orgSort; //当前数据的sort
        let index; //当前数据的index

        if (treeData != null && treeData.length > 0) {
            treeData.forEach(function (item, index) {
                if (item.orgPid == nodePid) {
                    ids.push(item)
                }
            });
        }

        //2) 根据id集合获取索引
        ids.forEach(function (item, index) {
            treeMap.set(item.id, index);
        });
        index = treeMap.get(node.id);
        let lastIndex = ids.length - 1;

        if (index + 1 > lastIndex) { //主要sort要从1开始或者取出来的数据要按orgSort拍好序，否则此处会报错
            layer.msg('已到达底部！', {icon: 1, time: 1000});
        } else {


            // 3) 获取下一条数据
            let upData = ids[index + 1];
            let upSort = upData.orgSort;

            // 4) 交换两条数据的orgSort
            node.value.orgSort = upSort;
            upData.orgSort = sort;

            // 5)把交换过的两条数据存入数组中
            idList.push(node.value);
            idList.push(upData);

            //6）通过ajax把数据发送到后台
            $.ajax({
                url: '/sys-org/move'
                , data: {'idList': JSON.stringify(idList)}
                , type: 'post'
                , success: function (res) {
                    if (res.code == 0) {
                        layer.msg("下移成功！", {icon: 1, time: 1000});
                        // 7) 刷新树（一定要注意更新数据库后执行此操作，不然下次上下移会报错）
                        loadOrgTree(moduleId);
                    } else {
                        layer.msg(res.msg, {icon: 5, time: 2000});
                    }

                },
                error: function (res) {
                    layer.msg(res.msg, {icon: 5, time: 2000});
                }
                , complete: function () {
                    currentTreeNode = null;
                }
            });

        }
    } else {
        layer.msg('请先点击树获取最新节点数据', {icon: 3, time: 2000});
    }
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData(values, pid, id, name) {
    var tree = [],
        item;

    var map = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();
        values[i].flag = 2;
        item.name = values[i][name];
        item.id = values[i][id];
        item.pid = values[i][id] ? 0 : values[i][id];
        item.value = JSON.stringify(values[i]).replace(/\"/g, "'")
        item.list = [];

        map.set(values[i][id], item);
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {
        if (values[i][pid] > 0) {
            var obj = map.get(values[i][pid]);
            obj.list.push(map.get(values[i][id]));
        } else {
            tree.push(map.get(values[i][id]));
        }
    }

    // 3)删除没有子项目的list
    // removeList(tree, 0);

    return tree;
}

/*
* @author: wj
* @description: 新增机构
* @date: 2018/12/14 14:17
* @param
* @return
*/
function addOrgCB() {
    if (!selectedModule && !currentTreeNode) {
        layer.msg("没有选择机构!");
        return;
    }

    var selectSysOrg = new Object();
    selectSysOrg.sysCate = selectedModule;
    selectSysOrg.parentOrg = currentTreeNode ? currentTreeNode : null;

    localStorage.sysOrg = JSON.stringify(selectSysOrg);

    let oldOpen;
    if (isAdmin) {
        if (selectSysOrg.parentOrg != null) {
            oldOpen = selectSysOrg.parentOrg.open;
        }
    }

    let height = selectSysOrg.parentOrg == null ? '580px' : '430px';

    layer.open({
        type: 2
        , title: '添加机构'
        , area: ['800px', `${height}`]
        , maxmin: false
        , content: 'sysOrgEdit.html?type=new&isAdmin=' + isAdmin + '&oldOpen=' + oldOpen
        , zIndex: layer.zIndex
        , end: function () {
            loadOrgTree(selectedModule.id);
        }
    });
}

function editOrgCB() {
    if (!selectedModule || !currentTreeNode) {
        layer.msg("没有选择机构!");
        return;
    }

    var selectSysOrg = new Object();
    selectSysOrg.sysCate = selectedModule;
    selectSysOrg.parentOrg = orgMap.get(currentTreeNode.orgPid) ? orgMap.get(currentTreeNode.orgPid) : null;
    selectSysOrg.currentOrg = currentTreeNode;

    localStorage.sysOrg = JSON.stringify(selectSysOrg);

    let oldOpen;
    if (selectSysOrg.parentOrg != null) {
        oldOpen = selectSysOrg.parentOrg.open;
    }

    let height = selectSysOrg.parentOrg == null ? '580px' : '430px';

    layer.open({
        type: 2
        , title: '修改机构'
        , area: ['800px', `${height}`]
        , maxmin: false
        , content: 'sysOrgEdit.html?type=edit&isAdmin=' + isAdmin + '&oldOpen=' + oldOpen
        , zIndex: layer.zIndex
        , end: function (res) {
            loadOrgTree(selectedModule.id);
            let sysOrg1 = JSON.parse(localStorage.sysOrg1);
            localStorage.removeItem(sysOrg1);
        }
    });
}

/**
 * 删除机构
 */
function removeOrg() {
    if (!selectedModule || !currentTreeNode) {
        layer.msg("没有选择机构!");
        return;
    }

    //询问框
    layer.confirm('确定要删除【' + currentTreeNode.orgName + '】吗？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        // 找到所有子节点放入data
        var ids = getOrgChilds([currentTreeNode.id]);
        ids.push(currentTreeNode.id);

        var data = [];
        for (var i = 0; i < ids.length; i++) {
            data.push(orgMap.get(ids[i]));
        }

        ActHttpRequest("/sys-org/delete/", {orgList: JSON.stringify(data)}, function (res) {
            if (res.code == 0) {
                loadOrgTree(selectedModule.id);
                clearOrg();
                layer.msg("删除成功！", {icon: 1, time: 1000})
            } else {
                layer.msg(res.msg, {icon: 5, time: 1000})

            }
        });
    });
}

/**
 * 还原
 */
function recoverOrg() {
    layer.open({
        type: 2,
        title: '机构回收站',
        area: ['800px', '600px'],
        maxmin: false,
        fixed: false, //不固定
        content: 'orgRecycle.html'
        , zIndex: layer.zIndexSysOperLog
        , end: function () {
            if (selectedModule) {
                loadOrgTree(selectedModule.id);
            }
        }
    });
}

/**
 * 清除选择的机构项
 */
function clearOrg() {
    currentTreeNode = null;
    $('.orgText').html(`<span style="color: #F72E29">${selectedModule.socName}</span>可以查看以下机构`);
    $("#functionTree").text('');
}

/**
 * 取得子节点id一览
 */
function getChilds(ids) {
    var result = [];

    for (value of orgMap) {
        if (ids.indexOf(value[1].orgPid) >= 0) {
            result.push(value[1].id);
        }
    }

    if (result.length > 0) {
        result = result.concat(getChilds(result));
    }

    return result;
}

/*
* @author: lxc
* @description: 加载关系企业功能
* @date: 2019/6/24 14:55
* @param
* @return
*/
function load_partner_table(orgId) {

    // table = $.extend(table, {config: {checkName: 'choiceFlag'}});

    if (orgId) {
        table.render({
            id: 'partnerLoad'
            , elem: '#test'
            , url: '/sys-org-partner/pageList'
            , where: {
                'orgId': orgId
            }
            , method: 'post'
            , limit: 5
            , limits: [5, 10, 15, 20, 25, 30, 35, 40]
            // , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , even: true//隔行变色
            , height: 330
            , cols: [[
                // {field: 'id', title: 'ID', width: 80, align: 'center', sort: true}
                {field: 'orgName', title: '机构名', align: 'left'}
                , {fixed: 'right', title: '操作', width: 100, align: 'center', toolbar: '#barDemo'}
            ]]
            , page: true
            , done: function (res, curr, count) {

            }
        });

        //监听行工具事件
        table.on('tool(test)', function (obj) {
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    $.ajax({
                        url: '/sys-org-partner/del',
                        type: 'post',
                        data: {
                            'id': data.id,
                            'updateTime': data.updateTime
                        },
                        success: function (res) {
                            if (res.code == 0) {
                                layer.msg("删除成功", {icon: 1});
                            } else {
                                layer.msg(res.msg, {icon: 5});
                            }
                        },
                        error: function () {
                            layer.msg('客户端向服务器请求失败', {icon: 5});
                        },
                        complete: function () {
                            load_partner_table(orgId);
                        }
                    })
                });
            }
        });

        table.on('checkbox(test)', function (obj) {
            let newOrgId = obj.data.orgId;
            let id = obj.data.id;
            let updateTime = obj.data.updateTime;
            let data = new Object();

            switch (obj.type) {
                case 'one':
                    if (obj.checked) {
                        data = {
                            'orgId': orgId,
                            'state': 1,
                            'targetOrgId': newOrgId,
                            'id': id,
                            'updateTime': updateTime
                        };

                        saveRootOrg(data, orgId);

                    } else {
                        data = {
                            'state': 2,
                            'targetOrgId': newOrgId,
                            'id': id,
                            'updateTime': updateTime
                        }

                        saveRootOrg(data, orgId);
                    }

                    break;

                case 'all':

                    break;
            }

        });
    }

}

/**
 * @author: wh
 * 保存根机构关联表
 */
function saveRootOrg(data, orgId) {
    $.ajax({
        url: '/sys-org-partner/save',
        type: 'post',
        traditional: true,
        data: {
            'id': orgId,
            'orgList': JSON.stringify(data)
        },
        success: function (res) {
            if (res.code == 0) {
                layer.msg('操作成功', {icon: 1});
            } else {
                layer.msg(res.msg, {icon: 5});
            }
            if (localStorage.company) {
                localStorage.removeItem('company');
            }
        },
        error: function (res) {
            layer.msg(res.msg, {icon: 5});
        },
        complete: function () {
            load_partner_table(orgId);
        }
    });
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatFunctionData(values, pid, id, name, checked) {
    var tree = [],
        item;

    var map = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.List.length; i++) {
        item = new Object();

        item.name = values.List[i][name];
        item.value = values.List[i][id];
        item.checked = values.List[i][checked];
        item.list = [];

        map.set(values.List[i][id], item);
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.List.length; i++) {
        if (values.List[i][pid] > 0) {
            var obj = map.get(values.List[i][pid]);
            obj.list.push(map.get(values.List[i][id]));
        } else {
            tree.push(map.get(values.List[i][id]));
        }
    }

    // 3)删除没有子项目的list
    for (var i = 0; i < values.List.length; i++) {
        var obj = map.get(values.List[i][id]);
        if (obj.list.length == 0) {
            delete obj.list;
        }
    }

    return tree;
}

/**
 * 取得授权功能子节点Id一览
 */
function getChilds(ids) {
    var result = [];

    for (value of privilageMap) {
        if (ids.indexOf(value[1].parentId) >= 0) {
            result.push(value[1].functionId);
        }
    }

    if (result.length > 0) {
        result = result.concat(getChilds(result));
    }

    return result;
}

/**
 * 取得授权机构子节点Id一览
 */
function getOrgChilds(ids) {
    var result = [];

    for (value of orgMap) {
        if (ids.indexOf(value[1].orgPid) >= 0) {
            result.push(value[1].id);
        }
    }

    if (result.length > 0) {
        result = result.concat(getOrgChilds(result));
    }

    return result;
}

/**
 * @author wh
 * @desc 添加根机构
 */
function add() {
    if (currentTreeNode) {
        let orgId = currentTreeNode.id;
        let index = layer.open({
            type: 2
            , title: '添加要查看的机构'
            , btn: ['保存', '取消']
            , zIndex: layer.zIndex
            , scrollbar: false
            // , shade: 0
            , content: ['orgSearch.html?orgId=' + orgId, 'no']
            , area: ['720px', '700px']
            , success: function () {

            }
            , yes: function () {
                if (localStorage.company) {
                    let company = JSON.parse(localStorage.company);
                    localStorage.removeItem(company);

                    if (company) {
                        saveRootOrg(company, orgId); //保存数据入库
                        layer.close(index);
                    } else {
                        layer.msg('请先选中要添加的单位!', {
                            icon: 5,
                            time: 1000 //2秒关闭（如果不配置，默认是3秒）
                        }, function () {
                            layer.close(index);
                        });
                    }
                } else {
                    layer.msg('请先选中要添加的单位!', {
                        icon: 5,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        layer.close(index);
                    });
                }

            }
            , btn2: function () {
                layer.close(index);
            }

        });
    }

}


/**
 * @author wh
 * @desc 部门切换
 */
function changeDepartment() {
    if (currentTreeNode && currentTreeNode.orgPid > 0) {
        let id = currentTreeNode.id;
        let updateTime = currentTreeNode.updateTime;
        layer.open({
            type: 1,
            title: '上级部门切换',
            btn: ['确定', '取消'],
            area: ['550px', '600px'],
            zIndex: layer.zIndex,
            shade: 0,
            content: $('#tree'),
            success: function () {
                //加载切换上级部门树
                loadDepTree(id);
            },
            yes: function () {
                let data = eval('(' + lastCheckedDep + ')');
                if (data) {
                    //提交数据到后台
                    $.ajax({
                        url: '/sys-org/changeDep'
                        , type: 'post'
                        , async: false
                        , data: {
                            'id': id,
                            'orgPid': data.id,
                            'ognId': data.ognId,
                            'orgSort': data.functionId,
                            'orgcate': data.orgCateId,
                            'updateTime': updateTime
                        }
                        , success: function (res) {
                            if (res.code == 0) {
                                layer.msg('切换成功', {icon: 1, time: 1000});
                            } else {
                                layer.msg(res.msg, {icon: 5, time: 2000});
                            }
                        }
                        , error: function () {
                            layer.msg("请求失败", {icon: 5, time: 2000});
                        }
                        , complete: function () {
                            if (selectedModule) {
                                loadOrgTree(selectedModule.id);
                            }
                        }
                    });
                } else {
                    layer.msg('请选择部门后再点击确定', {
                        icon: 5,
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        layer.closeAll();
                    });
                }


            },
            btn2: function () {
                layer.closeAll();
            }
            , end: function () {
            }
        })
    } else {
        layer.msg("请先选择部门", {icon: 5, time: 1000});
    }
}

function loadDepTree(id) {
    $.ajax({
        url: '/sys-org/getOrgTreeById',
        type: 'post',
        data: {'id': id},
        success: function (res) {
            if (res.code == 0) {

                let trees = formatData1(res.data, 'parentId', 'id', 'orgName', 'choiceFlag');

                authtree.render('#depTree', trees, {
                    inputname: 'authids[]',
                    layfilter: 'lay-check-auth',
                    autowidth: true,
                    checkType: 'radio',
                    flags: [2]
                });

                authtree.on('change(lay-check-auth)', function (data) {
                    // 获取所有最新中节点
                    lastCheckedDep = authtree.getLastChecked('#depTree');

                });

                authtree.showDept('#depTree', 2);

            } else {
                layer.msg(res.msg, {icon: 5});

            }
        }
    });
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData1(values, pid, id, name, checked) {
    var tree = [],
        item,
        obj;

    // 全局变量赋值
    let orgMap = new Map();
    let cateMap = new Map();
    let cateList = [];

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();

        item.id = values[i][id];
        item.name = values[i][name];
        item.value = JSON.stringify(values[i]).replace(/"/g, "'");
        item.checked = false;
        item.list = [];

        if (values[i].flag == 1) {
            cateMap.set(values[i][id], item);
            cateList.push(item);
        } else {
            item.orgCate = values[i]['orgCateId'];
            orgMap.set(values[i][id], item);
        }
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {
        if (values[i].flag > 1) {
            if (values[i][pid] > 0) {
                obj = orgMap.get(values[i][pid]);
                if (obj) {
                    obj.list.push(orgMap.get(values[i][id]));
                }
            } else {
                tree.push(orgMap.get(values[i][id]));
            }
        }
    }

    // 3)机构赋给机构分类
    for (let org of tree) {
        obj = cateMap.get(org.orgCate);
        delete org.orgCate;
        obj.list.push(org);
    }

    return cateList;
}

function formatData2(values, pid, id, name, checked) {
    var tree = [],
        item,
        obj,
        tmpObj,
        ognObj;

    // 全局变量赋值
    orgMap.clear();
    ognMap.clear();

    let postMap = new Map();
    let orgList = [];
    let cateMap = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();

        item.name = values[i][name];
        item.value = JSON.stringify(values[i]).replace(/"/g, "'");
        item.checked = values[i][checked];
        item.list = [];

        switch (values[i].flag) {
            case 1:
                item.name = values[i].orgName;
                cateMap.set(values[i].orgId, item);
                tree.push(item);
                break;
            case 2:
                orgMap.set(values[i][id], item);
                orgList.push(values[i]);

                if (values[i][pid] == 0) {
                    ognMap.set(values[i][id], values[i]);
                }

                break;
            case 3:
                postMap.set(values[i][id], item);
                break;
        }
    }

    // 2)插入默认岗位
    // 2.1) 在已有的表中把默认岗位的id和updateTIme加入进去
    if (orgList.length > 0) {
        orgList.map(item => {
            if (defPsArray.indexOf(item.orgId) > -1) {
                item.functionId = defPsMap.get(item.orgId).id;
                item.updateTime = defPsMap.get(item.orgId).updateTime;
            }
        });
    }

    for (var i = 0; i < orgList.length; i++) { // 遍历Array
        obj = orgMap.get(orgList[i][id]);
        ognObj = JSON.parse(obj.value.replace(/'/g, "\""));

        if (!orgList[i].roleId) continue;

        tmpObj = new Object();
        tmpObj.orgId = orgList[i][id];
        tmpObj.parentId = orgList[i][id];
        tmpObj.orgName = ognObj.orgName;
        tmpObj.functionId = orgList[i].functionId;
        tmpObj.updateTime = orgList[i].updateTime;

        ognObj = ognMap.get(orgList[i].ognId);
        tmpObj.postName = ognObj.postName;

        tmpObj.id = 0;
        tmpObj.postId = 0;
        tmpObj.flag = 3;

        item = new Object();
        item.name = tmpObj.postName;
        item.value = JSON.stringify(tmpObj).replace(/"/g, "'");
        item.checked = false;
        item.list = [];

        obj.list.push(item);
    }

    // 3)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {

        switch (values[i].flag) {
            case 1:
                break;
            case 2:
                if (values[i][pid] > 0) {
                    obj = orgMap.get(values[i][pid]);
                    obj.list.push(orgMap.get(values[i][id]));
                } else {
                    obj = cateMap.get(values[i].orgCateId);
                    obj.list.push(orgMap.get(values[i][id]));
                }

                break;
            case 3:
                obj = orgMap.get(values[i].orgId);

                if (obj.list.length > 0) {
                    obj.list.splice(obj.list.length - 1, 0, postMap.get(values[i][id]));
                } else {
                    obj.list.push(postMap.get(values[i][id]));
                }

                break;
        }
    }

    // 4)删除没有子项目的list
    removeList(tree, 0);

    return tree;
}

function removeList(list, level) {
    for (var i = list.length - 1; i >= 0; i--) {
        if (list[i].list && list[i].list.length == 0) {
            delete list[i].list;

            if (level == 0) {
                list.splice(i, 1);
            }
        } else {
            removeList(list[i].list, level + 1);
        }
    }
}

